<template>
  <div class="device-center-container">
    <!-- 上半部分 -->
    <div class="top-section">
      <!-- 左边：用户在线时长柱状图 -->
      <div class="chart-container left-chart">
        <h3>用户在线时长</h3>
        <div ref="userOnlineDurationChart" class="echart-instance"></div>
      </div>
      <!-- 右边：应用流量扇形图 -->
      <div class="chart-container right-chart">
        <h3>应用流量</h3>
        <div ref="appTrafficChart" class="echart-instance"></div>
      </div>
    </div>

    <!-- 下半部分：用户列表 -->
    <div class="bottom-section user-list-section">
      <div class="user-list-header">
        <h3>用户列表</h3>
        <div class="actions">
          <button class="action-button">黑白名单</button>
          <button class="action-button active">在线</button>
          <span class="filter-icon">
            <svg t="1691244999500" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4197" width="20" height="20"><path d="M950.190286 162.433143h-876.381714c-31.002286 0-56.202286 25.201143-56.202286 56.202286s25.201143 56.202286 56.202286 56.202286h876.381714c31.002286 0 56.202286-25.201143 56.202286-56.202286s-25.2-56.202286-56.202286-56.202286zM761.987429 455.798857H262.012571c-31.002286 0-56.202286 25.201143-56.202286 56.202286s25.201143 56.202286 56.202286 56.202286h499.974858c31.002286 0 56.202286-25.201143 56.202286-56.202286s-25.201143-56.202286-56.202286-56.202286zM541.182857 749.163429H482.817143c-31.002286 0-56.202286 25.201143-56.202286 56.202286s25.201143 56.202286 56.202286 56.202286h58.365714c31.002286 0 56.202286-25.201143 56.202286-56.202286s-25.2-56.202286-56.202286-56.202286z" p-id="4198" fill="#8a8a8a"></path></svg>
          </span>
        </div>
      </div>
      <div class="table-responsive">
        <table class="user-table">
          <thead>
            <tr>
              <th></th>
              <th>用户名</th>
              <th>终端MAC</th>
              <th>终端IP</th>
              <th>终端IPv6</th>
              <th>关联设备</th>
              <th>接入设备</th>
              <th>SSID</th>
              <th>接入类型</th>
              <th>认证方式</th>
              <th>认证状态</th>
              <th>丢包率</th>
              <th>网关丢...</th>
              <th>信噪比</th>
              <th>重传率</th>
              <th>接入终...</th>
              <th>协商速...</th>
              <th>在线时长</th>
              <th>...</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(user, index) in userList" :key="index">
              <td><span class="expand-icon">></span></td>
              <td>{{ user.username }}</td>
              <td class="mac-address">{{ user.mac }}</td>
              <td>{{ user.ip }}</td>
              <td>{{ user.ipv6 }}</td>
              <td>{{ user.assocDevice }}</td>
              <td>{{ user.accessDevice }}</td>
              <td>{{ user.ssid }}</td>
              <td>{{ user.accessType }}</td>
              <td>{{ user.authMethod }}</td>
              <td>{{ user.authStatus }}</td>
              <td :class="getStatusClass(user.packetLoss)">{{ user.packetLoss }}</td>
              <td>{{ user.gatewayLoss }}</td>
              <td :class="getStatusClass(user.snr)">{{ user.snr }}</td>
              <td :class="getStatusClass(user.retransmissionRate)">{{ user.retransmissionRate }}</td>
              <td>{{ user.accessTerminal }}</td>
              <td>{{ user.negotiatedSpeed }}</td>
              <td>{{ user.onlineDuration }}</td>
              <td>{{ user.actions }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts/core';
import { BarChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  PieChart,
  LegendComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);


export default {
  name: 'DeviceCenter',
  data() {
    return {
      userOnlineDurationChartInstance: null,
      appTrafficChartInstance: null,
      userOnlineData: {
        categories: ['1小时内', '1-2小时', '2-4小时', '4-6小时', '6-8小时', '8小时以上'],
        values: [1, 1, 1, 0, 0, 9]
      },
      appTrafficData: [ 
        { value: 30.1, name: 'QQLive', dataSize: '1.29GB' },
        { value: 24.0, name: 'HTTPS', dataSize: '1.03GB' },
        { value: 13.1, name: 'HTTP', dataSize: '574.15MB' },
        { value: 12.7, name: 'WeiXin_VoIP', dataSize: '558.02MB' },
        { value: 5.0, name: 'General_UDP', dataSize: '221.35MB' },
        { value: 15.1, name: 'Others', dataSize: '661.68MB' }
      ],
      userOnlineTimerId: null, 
      appTrafficTimerId: null,
      userList: [ // Sample user data based on the image
        {
          username: 'user001',
          mac: '04-CF-8...',
          ip: '192.168.100...',
          ipv6: '--',
          assocDevice: '1F 4050...',
          accessDevice: '98-35-E...',
          ssid: 'Day Of ...',
          accessType: '无线接入',
          authMethod: 'WPA2-P...',
          authStatus: 'None',
          packetLoss: '优 (0%)',
          gatewayLoss: '--',
          snr: '优 (44)',
          retransmissionRate: '优 (10%)',
          accessTerminal: '-51',
          negotiatedSpeed: '72',
          onlineDuration: '138小时 ...',
          actions: '8'
        },
        {
          username: 'user002',
          mac: '44-23-7...',
          ip: '192.168.100...',
          ipv6: '--',
          assocDevice: '1F 4050...',
          accessDevice: '98-35-E...',
          ssid: 'Day Of ...',
          accessType: '无线接入',
          authMethod: 'WPA2-P...',
          authStatus: 'None',
          packetLoss: '优 (0%)',
          gatewayLoss: '--',
          snr: '优 (40)',
          retransmissionRate: '优 (0%)',
          accessTerminal: '-55',
          negotiatedSpeed: '72',
          onlineDuration: '50小时 5...',
          actions: '7'
        },
        {
          username: 'user003',
          mac: '50-EC-5...',
          ip: '192.168.100...',
          ipv6: '--',
          assocDevice: '2F 4050...',
          accessDevice: '98-35-E...',
          ssid: 'Day Of ...',
          accessType: '无线接入',
          authMethod: 'WPA2-P...',
          authStatus: 'None',
          packetLoss: '优 (0%)',
          gatewayLoss: '--',
          snr: '优 (36)',
          retransmissionRate: '优 (0%)',
          accessTerminal: '-59',
          negotiatedSpeed: '72',
          onlineDuration: '1小时 38...',
          actions: '5'
        },
        {
          username: 'user004',
          mac: '80-68-E...',
          ip: '192.168.100...',
          ipv6: '--',
          assocDevice: '1F 4050...',
          accessDevice: '98-35-E...',
          ssid: 'Day Of ...',
          accessType: '无线接入',
          authMethod: 'WPA2-P...',
          authStatus: 'None',
          packetLoss: '优 (0%)',
          gatewayLoss: '--',
          snr: '优 (44)',
          retransmissionRate: '优 (1%)',
          accessTerminal: '-51',
          negotiatedSpeed: '866',
          onlineDuration: '27小时 9...',
          actions: '1'
        },
        {
          username: 'user005',
          mac: '34-D0-B...',
          ip: '192.168.100...',
          ipv6: '--',
          assocDevice: '2F 4050...',
          accessDevice: '98-35-E...',
          ssid: 'Day Of ...',
          accessType: '无线接入',
          authMethod: 'WPA2-P...',
          authStatus: 'None',
          packetLoss: '优 (0%)', // Image shows '良 (23)' for SNR, assuming packet loss is still '优'
          gatewayLoss: '--',
          snr: '良 (23)',
          retransmissionRate: '优 (0%)',
          accessTerminal: '-72',
          negotiatedSpeed: '65',
          onlineDuration: '18小时 3...',
          actions: '4'
        }
      ]
    };
  },
  mounted() {
    this.initUserOnlineDurationChart();
    this.initAppTrafficChart();
    window.addEventListener('resize', this.resizeCharts);

    this.userOnlineTimerId = setInterval(this.updateUserOnlineChartData, 3000); 
    this.appTrafficTimerId = setInterval(this.updateAppTrafficChartData, 3500); 
  },
  beforeUnmount() {
    if (this.userOnlineDurationChartInstance) {
      this.userOnlineDurationChartInstance.dispose();
    }
    if (this.appTrafficChartInstance) {
      this.appTrafficChartInstance.dispose();
    }
    window.removeEventListener('resize', this.resizeCharts);

    if (this.userOnlineTimerId) {
      clearInterval(this.userOnlineTimerId);
    }
    if (this.appTrafficTimerId) {
      clearInterval(this.appTrafficTimerId);
    }
  },
  methods: {
    initUserOnlineDurationChart() {
      if (this.$refs.userOnlineDurationChart) {
        this.userOnlineDurationChartInstance = echarts.init(this.$refs.userOnlineDurationChart);
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: this.userOnlineData.categories,
              axisTick: {
                alignWithLabel: true
              },
              axisLabel: {
                interval: 0,
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '人',
              max: 12 
            }
          ],
          series: [
            {
              name: '用户数',
              type: 'bar',
              barWidth: '60%',
              data: this.userOnlineData.values,
              itemStyle: {
                borderRadius: [5, 5, 0, 0], 
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ 
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              },
              emphasis: { 
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#2378f7' },
                    { offset: 0.7, color: '#2378f7' },
                    { offset: 1, color: '#83bff6' }
                  ])
                }
              },
              animationDuration: 600,
              animationEasing: 'elasticOut',
              animationDelayUpdate: function (idx) {
                return idx * 50; 
              }
            }
          ]
        };
        this.userOnlineDurationChartInstance.setOption(option);
      }
    },

    initAppTrafficChart() {
      if (this.$refs.appTrafficChart) {
        this.appTrafficChartInstance = echarts.init(this.$refs.appTrafficChart);
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: (params) => { 
              const originalItem = this.appTrafficData.find(d => d.name === params.name);
              if (originalItem) {
                return `${params.seriesName}<br/>${params.name}: ${originalItem.dataSize} (${params.percent}%)`;
              }
              return `${params.seriesName}<br/>${params.name}: ${params.percent}%`;
            }
          },
          legend: {
            orient: 'vertical',
            left: 'right',
            top: 'center',
            itemGap: 10,
            formatter: (name) => {
              const item = this.appTrafficData.find(d => d.name === name);
              if (item) {
                return `${name} ${item.dataSize} (${item.value}%)`;
              }
              return name;
            }
          },
          series: [
            {
              name: '应用流量',
              type: 'pie',
              radius: ['45%', '70%'], 
              center: ['50%', '50%'], 
              roseType: 'radius', 
              avoidLabelOverlap: true,
              itemStyle: {
                borderRadius: 8,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                scaleSize: 15, 
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold',
                  formatter: '{b}\n{d}%'
                }
              },
              labelLine: {
                show: false
              },
              data: this.appTrafficData.map(item => ({ value: item.value, name: item.name })),
              color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'], 
              animationDuration: 800,
              animationEasing: 'cubicInOut',
              animationDelay: function (idx) {
                return Math.random() * 200; 
              }
            }
          ]
        };
        this.appTrafficChartInstance.setOption(option);
      }
    },

    updateUserOnlineChartData() {
      if (this.userOnlineDurationChartInstance) {
        const newValues = this.userOnlineData.values.map(() => Math.max(0, Math.floor(Math.random() * 12)));
        this.userOnlineData.values = newValues; 
        this.userOnlineDurationChartInstance.setOption({
          series: [{
            data: newValues
          }]
        });
      }
    },

    updateAppTrafficChartData() {
      if (this.appTrafficChartInstance) {
        let totalValue = 0;
        const newSeriesData = this.appTrafficData.map(item => {
          const newValue = Math.max(5, Math.random() * 30); 
          totalValue += newValue;
          return { name: item.name, value: newValue, dataSize: item.dataSize }; 
        });

        const normalizedData = newSeriesData.map(item => ({
            name: item.name,
            value: parseFloat(((item.value / totalValue) * 100).toFixed(1)), 
            dataSize: item.dataSize 
        }));
        
        this.appTrafficData = normalizedData.map(item => ({
            name: item.name,
            value: item.value, 
            dataSize: item.dataSize 
        }));


        this.appTrafficChartInstance.setOption({
          legend: { 
             formatter: (name) => {
              const item = this.appTrafficData.find(d => d.name === name);
              if (item) {
                return `${name} ${item.dataSize} (${item.value}%)`;
              }
              return name;
            }
          },
          series: [{
            data: this.appTrafficData.map(item => ({value: item.value, name: item.name}))
          }]
        });
      }
    },

    resizeCharts() {
      if (this.userOnlineDurationChartInstance) {
        this.userOnlineDurationChartInstance.resize();
      }
      if (this.appTrafficChartInstance) {
        this.appTrafficChartInstance.resize();
      }
    },
    getStatusClass(statusValue) {
      if (typeof statusValue !== 'string') return '';
      if (statusValue.startsWith('优')) return 'status-excellent';
      if (statusValue.startsWith('良')) return 'status-good';
      if (statusValue.startsWith('中')) return 'status-medium';
      if (statusValue.startsWith('差')) return 'status-poor';
      return '';
    }
  }
};
</script>

<style scoped>
.device-center-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  font-size: 13px; /* Adjusted base font size */
}

.top-section {
  display: flex;
  min-height: 300px; /* Adjusted from 350px if space is tight */
  margin-bottom: 20px;
  gap: 20px;
}

.left-chart, .right-chart {
  flex: 1;
  border: 1px solid #e0e0e0; /* Lighter border */
  padding: 15px;
  border-radius: 6px; /* Slightly smaller radius */
  background-color: #fff; /* White background for charts */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* Subtle shadow */
}

.chart-container h3 {
  text-align: left; /* Align title to left as per image */
  margin-bottom: 15px;
  flex-shrink: 0;
  font-size: 16px;
  color: #333;
  padding-left: 5px; /* Small padding for title */
}

.echart-instance {
  width: 100%;
  height: 100%;
  min-height: 250px; /* Adjusted from 300px */
  flex-grow: 1;
}

.bottom-section.user-list-section { /* Renamed for clarity */
  flex: 1.5; /* Give more space to the list if needed */
  border: 1px solid #e0e0e0;
  padding: 15px;
  border-radius: 6px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  min-height: 300px; /* Ensure enough height for the table */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.user-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 5px;
}

.user-list-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  color: #606266;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.action-button.active {
  background-color: #409eff; /* Element UI primary blue */
  color: #fff;
  border-color: #409eff;
}

.action-button:hover {
  border-color: #c0c4cc;
}

.action-button.active:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.filter-icon {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.filter-icon svg {
 fill: #606266; /* Icon color */
}

.table-responsive {
  overflow-x: auto; /* Allow horizontal scrolling for table */
  flex-grow: 1;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px; /* Smaller font for table content */
}

.user-table th,
.user-table td {
  border-bottom: 1px solid #ebeef5; /* Element UI table border color */
  padding: 10px 8px; /* Adjusted padding */
  text-align: left;
  white-space: nowrap; /* Prevent text wrapping */
}

.user-table th {
  background-color: #f5f7fa; /* Element UI table header background */
  color: #909399; /* Element UI table header text color */
  font-weight: 500;
}

.user-table tbody tr:hover {
  background-color: #f5f7fa;
}

.expand-icon {
  color: #409eff;
  cursor: pointer;
  font-weight: bold;
  display: inline-block;
  margin-right: 5px;
}

.mac-address {
  color: #409eff; /* Blue color for MAC address like in image */
  cursor: pointer;
}
.mac-address:hover {
  text-decoration: underline;
}

.status-excellent {
  color: #67c23a; /* Green for '优' */
}
.status-good {
  color: #e6a23c; /* Orange for '良' */
}
.status-medium {
  color: #f56c6c; /* Red for '中' (example) */
}
.status-poor {
  color: #909399; /* Grey for '差' (example) */
}

/* Placeholder styles if needed */
.placeholder-list {
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #aaa;
  color: #777;
  background-color: #fff;
}
</style>